// dao/userDao.js
// 实现与MYSQL交互

var mysql = require('mysql');
var $conf = require('../conf/db');
//var $util = require('../util/util');
var $sql  = require('./userSQLmapping');

//使用连接池
//var pool = mysql.createPool($util.extend({},$conf.mysql));
var pool = mysql.createPool($conf.mysql);

//向前台返回json方法
var jsonWrite = function (res,ret) {
    if(typeof ret === 'undefined'){
        res.json({
            code :'1',
            msg:'操作失败'
        });
    } else {
        res.json(ret);
    }
};

module.exports = {
  add:function (req,res,next) {
      pool.getConnection(function (err,connection) {
          //获取前台页面传入参数
          var param = req.query || req.params;

          //建立连接，向表中插入值
          //'INSERT INTO user(id,name,age,) VALUES(0,?,?)'
          connection.query($sql.insert,[param.name,param.age],function (err,result) {
              if(result){
                  result = {
                      code:200,
                      msg:'增加成功'
                  };
              }

              //以json形式，把操作结果返给前端
              jsonWrite(res,result);

              //释放链接
              connection.release();
          })
      })
  }
};